﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;
using System.Xml;
using Chemistry.Models;
using GLCommon;
using Newtonsoft.Json;

namespace Chemistry.Tools
{
    public class Tool
    {

        public static ConfigModel GetConfig()
        {
            ConfigModel config = null;
            using (FileStream fs = new FileStream(Global.CONFIGDATA_PATH, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                try
                {
                    if (fs.Length > 0)
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        config = (ConfigModel)formatter.Deserialize(fs);
                    }
                    else
                    {
                        config = new ConfigModel();
                    }
                }
                catch (Exception ex)
                {
                    LogTool.WriteErrorLog(ex);
                }
            }
            return config;
        }

        /// <summary>
        /// 根据类名获取流程命令配置
        /// </summary>
        /// <param name="classname"></param>
        /// <returns></returns>
        public static FlowCommand GetFlowCommand(string classname)
        {
            FlowCommand command = null;
            try
            {
                using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "flowcommand.txt", FileMode.Open))
                {
                    StreamReader sr = new StreamReader(fs);
                    string content = sr.ReadToEnd();
                    var commands = JsonConvert.DeserializeObject<List<FlowCommand>>(content);
                    command = commands.SingleOrDefault(i => i.Title == classname);
                }
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex);
            }
            return command;
        }

        /// <summary>
        /// 获取可调节按钮配置
        /// </summary>
        /// <param name="classname">
        ///  类名.
        /// </param>
        /// <returns>
        /// </returns>
        public static RegulationButtonConfig GetRegulationButtons(string classname)
        {
            RegulationButtonConfig config = null;
            try
            {
                FileStream fs = new FileStream(
                    AppDomain.CurrentDomain.BaseDirectory + "RegulationButtonConfig.txt",
                    FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                StreamReader sr = new StreamReader(fs);
                string content = sr.ReadToEnd();
                var c = JsonConvert.DeserializeObject<List<RegulationButtonConfig>>(content);
                config = c.SingleOrDefault(i => i.ClassName == classname);
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex);
            }
            return config;
        }

        public static bool CanUpdate(ref string version)
        {
            try
            {
                //得到本地版本
                string localversion = GetConfigValue("UpDateTime");
                //得到服务器更新版本日期
                string serverVersion = GetServerVersion();
                //服务器和本地更新日期不为空
                if (!string.IsNullOrEmpty(localversion) && !string.IsNullOrEmpty(serverVersion))
                {
                    var local = int.Parse(Regex.Replace(localversion, @"[^\d]", ""));
                    var server = int.Parse(Regex.Replace(serverVersion, @"[^\d]", ""));
                    version = serverVersion;
                    return server > local;

                }
                return false;
            }
            catch (Exception ex)
            {
                LogTool.UpServerLog(ex.Message, GLCommon.EventType.Error);
                return false;
            }
        }
        static string GetServerVersion()
        {
            string serverUrl = GetConfigValue("Url");
            string serverPath = GetConfigValue("UpdateFilePath");
            string serverDir = serverUrl + serverPath + "/AutoUpdate.xml";
            string lastVersion = "";
            try
            {
                WebRequest wReq = WebRequest.Create(serverDir);
                wReq.Timeout = 3000;
                WebResponse wResp = wReq.GetResponse();
                Stream respStrem = wResp.GetResponseStream();
                XmlTextReader xml = new XmlTextReader(respStrem);
                while (xml.Read())
                {
                    if (xml.Name == "UpdateTime")
                    {
                        lastVersion = xml.GetAttribute("Date");
                        break;
                    }
                }
                xml.Close();
                respStrem.Close();
                return lastVersion;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 根据key获取配置文件中的value
        /// </summary>
        /// <param name="key">appSetting的key</param>
        /// <returns></returns>
        public static string GetConfigValue(string key)
        {
            string value = String.Empty;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = config.AppSettings.Settings;
            var item = settings[key];
            if (item == null)
            {
                config.AppSettings.Settings.Add(key, "");
            }
            else
            {
                value = item.Value;
            }
            return value;
        }


        public class FlowCommand
        {
            public string Title { get; set; }
            public List<NameValue> Items { get; set; }

        }

        public class NameValue
        {
            public string Name { get; set; }
            public string Value { get; set; }
        }


        public static List<ButtonConfig> GetButtons()
        {
            List<ButtonConfig> buttons = null;
            try
            {
                FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "buttonconfig.txt", FileMode.Open);
                StreamReader sr = new StreamReader(fs);
                string content = sr.ReadToEnd();
                buttons = JsonConvert.DeserializeObject<List<ButtonConfig>>(content);
            }
            catch (Exception ex)
            {
                LogTool.WriteErrorLog(ex);
            }
            return buttons;
        }

       

        /// <summary>
        /// 按钮配置（主界面）
        /// </summary>
        public class ButtonConfig
        {
            public string Name { get; set; }
            public bool IsInner { get; set; }
            public string ClassName { get; set; }
            public bool IsShow { get; set; }

            public string WorkflowChineseName { get; set; }
        }

        /// <summary>
        /// 可调节按钮 的配置
        /// </summary>
        public class RegulationButtonConfig
        {
            public string ClassName { get; set; }

            public List<ConfigName> Items { get; set; }

            public class ConfigName
            {
                public string Name { get; set; }
            }
        }

    }


}
